package com.bxd.baodan.util;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Service;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager.NameNotFoundException;
import android.net.ConnectivityManager;
import android.os.Handler;
import android.os.Looper;
import android.provider.Settings;
import android.text.TextUtils;
import android.widget.Toast;

import com.bxd.baodan.App;
import com.bxd.baodan.app.Constant;
import com.bxd.baodan.app.LoginInfo;
import com.bxd.baodan.app.SharedPreferanceKey;
import com.bxd.baodan.interfaces.OnNetFailListener;
import com.bxd.baodan.util.net.M509TrustManager;
import com.bxd.baodan.util.net.MyHostnameVerifier;
import com.bxd.baodan.util.net.SSLSocketFactoryCompat;
import com.bxd.baodan.widget.CustomProgressDialog;

import org.json.JSONException;

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.File;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.SocketTimeoutException;
import java.net.URL;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.TrustManager;

import okhttp3.FormBody;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;


/**
 * 网络接口,post请求string或者get请求json,里面只包含一个线程,只能同时发送一个网络请求
 *
 * @author oldfeel
 */
public class NetUtil extends Handler {
    // 异地登陆
    public static final int NET_ERROR_OTHER_LOGIN = 1005;
    public static final int NET_ERROR_WRONG_PWD = 1004;
    /**
     * 打开网络连接
     */
    public static final int OPEN_NETWORK = -1;
    /**
     * 超时时间限制
     */
    public static final int TIME_OUT = 8 * 1000;
    public static OkHttpClient okHttpClient;
    public CustomProgressDialog pd;
    public String API;
    Map<String, Object> params = new HashMap<String, Object>();
    Map<String, File> files = new HashMap<String, File>();
    private Activity activity;
    private Thread requestThread;
    private AlertDialog dialog;
    private String path;

    // private Handler myHandler;
    private OnNetFailListener failListener;
    private Long currentTime;

    /**
     * 构造一个netapi对象
     *
     * @param activity
     * @param api      这次请求需要调用的api
     */
    public NetUtil(Activity activity, String api) {
        this.activity = activity;
        // creatHandler();
        API = api;

        //  this.path = JsonApi.path + api;
        this.path = Constant.root_url + api + "?";
        try {
            setParams("uid", LoginInfo.getInstance(activity).getUser()
                    .getU_id());
            setParams("pwd", LoginInfo.getInstance(activity).getUser().getPwd());
            setParams("deviceType", Utils.getDeviceType());
            setParams("imei", Utils.getDeciveId(activity));// 设备标识码
            setParams("ver", "android-" + VersionUtil.getVersionName(activity));

        } catch (Exception e) {
            // TODO: handle exception
        }
        // setParams("test", "bxdwenwen5971");//测试时为了更详细的描述请求的错误信息，当正式上线时该参数并不上传
    }


    public NetUtil(String api, Activity activity) {
        this.activity = activity;
        API = api;
        String base = Constant.root_url + "api/";
        this.path = base + api + "?";
        try {
            setParams("uid", LoginInfo.getInstance(activity).getUser()
                    .getU_id());
            setParams("pwd", LoginInfo.getInstance(activity).getUser().getPwd());
            setParams("deviceType", Utils.getDeviceType());
            setParams("imei", Utils.getDeciveId(activity));// 设备标识码
            setParams("ver", "android-" + VersionUtil.getVersionName(activity));

        } catch (Exception e) {
            // TODO: handle exception
        }
    }

    public NetUtil(Service service, String api) {


        API = api;

        this.path = Constant.root_url + api + "?";
        try {
            setParams("uid", LoginInfo.getInstance(service).getUser()
                    .getU_id());
            setParams("pwd", LoginInfo.getInstance(service).getUser().getPwd());
            setParams("deviceType", Utils.getDeviceType());
            setParams("imei", Utils.getDeciveId(service));// 设备标识码
            setParams("ver", "android-" + VersionUtil.getVersionName(service));

        } catch (Exception e) {

        }
    }

    /**
     * 判断网络连接
     */
    public static boolean isNetworkConnect(Context context) {
        try {
            ConnectivityManager cm = (ConnectivityManager) context
                    .getSystemService(Context.CONNECTIVITY_SERVICE);
            cm.getActiveNetworkInfo();
            if (cm.getActiveNetworkInfo() != null) {
                return cm.getActiveNetworkInfo().isAvailable();
            }
        } catch (Exception e) {
            // TODO: handle exception
        }
        return false;
    }

    public void setFile(String key, File file) {
        files.put(key, file);
    }

    /**
     * 添加参数
     *
     * @param key
     * @param value
     */
    public void setParams(String key, Object value) {
        if (!isEmpty(key) && !isEmpty(value)) {
            params.put(key.trim(), value.toString().trim());// *.trim(),取消首尾空格
        }
    }

    public void clearParams() {
        if (params != null) {
            params.clear();
        }
    }

    public void clearParams(String key) {
        if (params != null) {
            params.remove(key);
        }
    }

    /**
     * 检查该参数是否有内容,没有的话就不用添加了
     *
     * @param str
     * @return true为没有内容, false为有内容
     */
    public boolean isEmpty(Object str) {
        if (str == null || str.toString().length() == 0)
            return true;
        else
            return false;
    }

    /**
     * 显示进度条提示
     *
     * @param message
     */
    public void showPd(String message) {
        if (message == null || message.length() == 0) {
            return;
        }
        if (pd != null) {
            pd.cancel();
            pd.dismiss();
            pd = null;
        }
        Activity curActivity = AppManager.getInstance().currentActivity();
        if (curActivity == null) {
            return;
        }

        pd = new CustomProgressDialog(curActivity, message);
        pd.setCanceledOnTouchOutside(false);
        pd.setOnCancelListener(new DialogInterface.OnCancelListener() {

            @Override
            public void onCancel(DialogInterface dialog) {
                if (failListener != null) {
                    failListener.cancel();

                }
                if (requestThread != null) {
                    requestThread.interrupt();
                }
            }
        });
        pd.setCancelable(true);
        /* fixme 18 2 2  android.view.WindowManager$BadTokenException: Unable to add window -- token android.os.BinderProxy@5ecd396 is not valid; is your activity running?*/
        if (!curActivity.isFinishing()) {
            pd.show();
        }
    }

    private boolean isLoginInforOK(String result) {
        boolean isLoginOk = true;
        if (NET_ERROR_WRONG_PWD == JSONUtil.getCode(result)) {
            isLoginOk = false;
        }
        return isLoginOk;
    }

    private boolean isAcountValue(String result) {
        boolean isLoginOk = true;
        if (NET_ERROR_OTHER_LOGIN == JSONUtil.getCode(result)) {
            isLoginOk = false;
            // Toast.makeText(activity, "账号在异地登录，请重新登录",
            // Toast.LENGTH_SHORT).show();
        }
        return isLoginOk;
    }

    /**
     * 发起一个post请求,返回string对象
     *
     * @param stringListener true 为加载缓存，false为不加载缓存
     */
    public void postRequest(final String text, final Context activity, final RequestStringListener stringListener) {
        if (!isNetworkConnect(App.getContext())) {
            App.getContext().sendBroadcast(
                    new Intent(Constant.ACTION_NO_INTERNET));
            Toast.makeText(App.getContext(), "似乎已断开了网络连接", Toast.LENGTH_SHORT).show();
            return;
        }
        showPd(text);
        Runnable task = new Runnable() {

            @Override
            public void run() {
                try {
                    final String result = postStringResult()/*okPost()*/;

                    if (result != null && !"".equals(result)) {
                        if (!isAcountValue(result)) {
                            SpUtil.getInstance().savaBoolean(
                                    SharedPreferanceKey.IS_RELOGIN, true);
                            LoginInfo.getInstance(activity).cancelLogin(
                                    activity);
                        }
                    }
                    if (requestThread.isInterrupted()) {
                        showLog("is interrupted");
                        return;
                    }
                    if (result == null || TextUtils.isEmpty(result)) {
                        netError();
                        return;
                    }
                    post(new Complete() {

                        @Override
                        public void run() {
                            super.run();
                            if (stringListener != null) {
                                if (isLoginInforOK(result)) {
                                    stringListener.onComplete(result);

                                } else {
                                    stringListener.onError(result);
                                    LoginInfo.getInstance(activity)
                                            .cancelLogin(activity);
                                }
                            }
                        }
                    });
                } /*catch (SocketTimeoutException e) {
                    timeOut(text, stringListener);
                    e.printStackTrace();
                } */ catch (Exception e) {
                    netError();
                    e.printStackTrace();
                }

            }
        };
        requestThread = new Thread(task);
        requestThread.start();
    }

    public void postRequest(final String text,
                            final RequestStringListener stringListener) {

        if (!isNetworkConnect(activity)) {
            App.getContext().sendBroadcast(
                    new Intent(Constant.ACTION_NO_INTERNET));
            if (activity != null) {

                Toast.makeText(activity, "似乎已断开了网络连接", Toast.LENGTH_SHORT).show();
            }
            // whetherOpenNet();
            return;
        }
        showPd(text);
        Runnable task = new Runnable() {

            @Override
            public void run() {
                try {
                    final String result = postStringResult()/*okPost()*/;

                    //打断点
                    if (result != null && !"".equals(result)) {
                        if (!isAcountValue(result)) {
                            SpUtil.getInstance().savaBoolean(
                                    SharedPreferanceKey.IS_RELOGIN, true);
                            LoginInfo.getInstance(activity).cancelLogin(
                                    activity);
                        }
                    }
                    if (requestThread.isInterrupted()) {
                        showLog("is interrupted");
                        return;
                    }
                    if (result == null || TextUtils.isEmpty(result)) {
                        netError();
                        return;
                    }
                    post(new Complete() {

                        @Override
                        public void run() {
                            super.run();
                            if (stringListener != null) {
                                if (isLoginInforOK(result)) {
                                    if (JSONUtil.isSuccess(result)) {
                                        stringListener.onComplete(result);
                                    } else {
                                        stringListener.onError(result);
                                        LogUtil.e("错误代码: " + JSONUtil.getCode(result));

                                    }

                                } else {
                                    LoginInfo.getInstance(activity)
                                            .cancelLogin(activity);
                                }
                            }
                        }
                    });
                } catch (Exception e) {
                    netError();
                    e.printStackTrace();
                }

            }
        };
        requestThread = new Thread(task);
        requestThread.start();
    }

    public void postRequest(String text,
                            final DataListener dataListener) {

        if (!isNetworkConnect(activity)) {
            App.getContext().sendBroadcast(
                    new Intent(Constant.ACTION_NO_INTERNET));
            if (activity != null) {

                Toast.makeText(activity, "似乎已断开了网络连接", Toast.LENGTH_SHORT).show();
            }
            // whetherOpenNet();
            return;
        }

        showPd(text);
        Runnable task = new Runnable() {

            @Override
            public void run() {
                try {
                    final String result = postStringResult()/*okPost()*/;

                    //打断点
                    if (result != null && !"".equals(result)) {
                        if (!isAcountValue(result)) {
                            SpUtil.getInstance().savaBoolean(
                                    SharedPreferanceKey.IS_RELOGIN, true);
                            LoginInfo.getInstance(activity).cancelLogin(
                                    activity);
                        }
                    }
                    if (requestThread.isInterrupted()) {
                        showLog("is interrupted");
                        return;
                    }
                    if (result == null || TextUtils.isEmpty(result)) {
                        netError();
                        return;
                    }
                    post(new Complete() {

                        @Override
                        public void run() {
                            super.run();
                            if (dataListener != null) {
                                if (isLoginInforOK(result)) {
                                    if (JSONUtil.isSuccess(result)) {
                                        dataListener.onComplete(JSONUtil.getData(result));
                                    } else {
                                        dataListener.onError(result);
                                        LogUtil.e("错误代码: " + JSONUtil.getCode(result));

                                    }

                                } else {
                                    LoginInfo.getInstance(activity)
                                            .cancelLogin(activity);
                                }
                            }
                        }
                    });
                } catch (Exception e) {
                    netError();
                    e.printStackTrace();
                }

            }
        };
        requestThread = new Thread(task);
        requestThread.start();
    }

    /**
     * 网络连接超时
     *
     * @param text
     * @param stringListener
     */
    protected void timeOut(final String text,
                           final RequestStringListener stringListener) {
        Looper.prepare();
        post(new Complete() {

            @Override
            public void run() {
                super.run();
                if (failListener != null) {
                    failListener.onTimeOut();
                }
                new AlertDialog.Builder(activity)
                        .setTitle("网络连接超时")
                        .setNegativeButton("取消", null)
                        .setPositiveButton("重连",
                                new DialogInterface.OnClickListener() {
                                    @Override
                                    public void onClick(DialogInterface dialog,
                                                        int which) {
                                        showLog("重连");
                                        postRequest(text, stringListener);
                                    }
                                }).show();
            }
        });
    }

    /**
     * 网络连接错误或返回数据为空
     */
    protected void netError() {
        if (Looper.myLooper() == null) {
            Looper.prepare();
        }
        post(new Complete() {
            @Override
            public void run() {
                super.run();
                if (failListener != null) {
                    failListener.onError();
                }
                if (!isNetworkConnect(activity)) {
                    whetherOpenNet();
                } else {
                    Toast.makeText(activity, "网络连接失败,请稍后重试", Toast.LENGTH_SHORT)
                            .show();
                }
            }
        });
    }

    /**
     * 发送post上传文件,获取字符串结果
     * <p>
     * true为加载缓存，false为不加载缓存
     *
     * @throws JSONException
     * @throws NameNotFoundException
     * @throws Exception
     */
    public String postStringResult() throws SocketTimeoutException,
            JSONException, NameNotFoundException {
        try {

            currentTime = System.currentTimeMillis();
            URL url = new URL(path);
            SSLContext sc = SSLContext.getInstance("TLS");
            sc.init(null, new TrustManager[]{new M509TrustManager()},
                    null);
            HttpsURLConnection
                    .setDefaultSSLSocketFactory(sc.getSocketFactory());
            HttpsURLConnection
                    .setDefaultHostnameVerifier(new MyHostnameVerifier());
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            // httpClient.getParams().setParameter("http.useragent",
            // getUserAgent());
            conn.setRequestProperty("User-Agent", getUserAgent()); // TODO
            conn.setDoOutput(true);
            conn.setDoInput(true);
            conn.setRequestMethod("POST");
            conn.setConnectTimeout(TIME_OUT);
            conn.setReadTimeout(TIME_OUT);
            conn.connect();
            DataOutputStream outStream = new DataOutputStream(
                    conn.getOutputStream());
            StringBuilder builder = new StringBuilder();
            if (params != null) {
                md5Map(params);

                for (String name : params.keySet()) {
                    builder.append("&"
                            + URLEncoder.encode(name, "utf-8")
                            + "="
                            + URLEncoder.encode(params.get(name).toString(),
                            "utf-8"));
                }
                builder.deleteCharAt(0);
                outStream.writeBytes(builder.toString());
            }
            LogUtil.e("get url ------> " + "\n" + path + builder.toString());

            if (conn.getResponseCode() == HttpURLConnection.HTTP_OK) {
                StringBuffer out = new StringBuffer();
                BufferedReader input = new BufferedReader(
                        new InputStreamReader(conn.getInputStream()));
                String line = null;
                while ((line = input.readLine()) != null) {
                    out.append(line);
                }
                input.close();

                String data = out.toString();
                LogUtil.e("get data ----> " + "\n" + data);
                return data;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    public OkHttpClient getOkHttpClient() {
        // FIXME: 2017/6/8 javax.net.ssl.SSLProtocolException: SSL handshake aborted: ssl=0xb8c471e0: Failure in SSL library, usually a protocol error
        // FIXME:    error:14077102:SSL routines:SSL23_GET_SERVER_HELLO:unsupported protocol
        OkHttpClient.Builder builder = new OkHttpClient.Builder();
        M509TrustManager trust = new M509TrustManager();
        final SSLSocketFactory sslSocketFactory = new SSLSocketFactoryCompat(trust);
        OkHttpClient okHttpClient = builder
                //  sslSocketFactory(sc.getSocketFactory())
                .sslSocketFactory(sslSocketFactory, trust)
                .hostnameVerifier(new MyHostnameVerifier())
                .connectTimeout(8, TimeUnit.SECONDS)
                .readTimeout(8, TimeUnit.SECONDS)
                .build();
        return okHttpClient;
    }

    public String okPost() {
        FormBody.Builder bodyBuilder = new FormBody.Builder(); //requestBody
        //okHttpClient
        if (okHttpClient == null) {
            okHttpClient = getOkHttpClient();
        }
        //当前时间,是参数,参与签名
        currentTime = System.currentTimeMillis();

        try {
            if (params != null) {
                //加密参数
                md5Map(params);
                //存储url
                StringBuilder sb = new StringBuilder();
                for (String key : params.keySet()) {

                    // TODO: 2017/7/15 测试是不是encode的问题
                    //post参数
                    //                    bodyBuilder.add(URLEncoder.encode(key.jks, "utf-8"),
                    //                            URLEncoder.encode(params.get(key.jks).toString(), "utf-8"));
                    // FIXME: 2017/7/15 签名校验问题解决,encode的问题
                    bodyBuilder.add(key, params.get(key).toString());

                    //拼接url
                    sb.append("&");
                    sb.append(String.format("%s=%s", URLEncoder.encode(key, "utf-8"),
                            URLEncoder.encode(params.get(key).toString(), "utf-8")));
                }
                //方便查看url
                LogUtil.e("get -ok- url ------> " + "\n" + path + sb.toString());
            }
            //请求
            Request request = new Request
                    .Builder()
                    .url(path)
                    .post(bodyBuilder.build()) //requestBody
                    .addHeader("User-Agent", getUserAgent())
                    .build();
            //响应
            Response response = okHttpClient.newCall(request).execute();

            String result = response.body().toString();

            LogUtil.e("get -ok- data ------> " + "\n" + result);
            if (response.isSuccessful()) {
                // json数据
                return result;
            }

        } catch (Exception e) {
            LogUtil.e("exception: " + e.toString());
            e.printStackTrace();
        }
        return null;
    }

    private Map<String, Object> md5Map(Map<String, Object> params) {
        try {
            params.remove("signature");  // FIXME: 2017/7/15 修复签名不对的bug,由于涉及到修改框架,暂时只做简单处理
        } catch (Exception e) {
            e.printStackTrace();
        }

        currentTime = System.currentTimeMillis();
        params.put("appid", Constant.APP_ID);
        params.put("expires", currentTime);
        params.put("appsecret", Constant.APP_SECRET);
        //   params.put("r", API);

        Iterator iter = params.entrySet().iterator();
        StringBuilder pp = new StringBuilder();
        while (iter.hasNext()) {
            Map.Entry entry = (Map.Entry) iter.next();
            String key = entry.getKey().toString();
            String val = entry.getValue().toString();
            pp.append(key + "=" + val + ",");

        }

        // 进行排序加密
        List<Map.Entry<String, Object>> mHashMapEntryList = new ArrayList<>(params.entrySet());

        Collections.sort(mHashMapEntryList,
                new Comparator<Map.Entry<String, Object>>() {

                    @Override
                    public int compare(Map.Entry<String, Object> firstMapEntry,
                                       Map.Entry<String, Object> secondMapEntry) {
                        return firstMapEntry.getKey().compareTo(
                                secondMapEntry.getKey());
                    }
                });

        StringBuilder sb = new StringBuilder();


        for (int i = 0; i < mHashMapEntryList.size(); i++) {
            if (i == 0) {
                sb.append(mHashMapEntryList.get(i).getKey() + "="
                        + mHashMapEntryList.get(i).getValue().toString());
            } else {
                sb.append("&" + mHashMapEntryList.get(i).getKey() + "="
                        + mHashMapEntryList.get(i).getValue().toString());

            }
        }

        String signature = DesUtil.md5(sb.toString());
        params.remove("appsecret");
        params.put("signature", signature);

        return params;
    }

    /**
     * 打开网络对话框
     */
    private void whetherOpenNet() {
        try {
            if (dialog != null) {
                dialog.cancel();
                dialog = null;
            }
            AlertDialog.Builder builder = new AlertDialog.Builder(activity);
            builder.setTitle("网络木有连接");
            builder.setMessage("是否打开网络连接");
            builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {

                @Override
                public void onClick(DialogInterface dialog, int which) {
                    activity.startActivity(new Intent(
                            Settings.ACTION_WIRELESS_SETTINGS));
                }
            });
            builder.setNegativeButton("取消", null);
            dialog = builder.create();
            dialog.show();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 打印日志
     *
     * @param log
     */
    private void showLog(String log) {
        LogUtil.e(log);
    }

    /**
     * 获取当前NetApi绑定的activity
     *
     * @return
     */
    public Activity getActivity() {
        return this.activity;
    }

    /**
     * 取消网络请求监听。。。
     *
     * @param cancelListener
     */
    public void setOnNetFailListener(OnNetFailListener cancelListener) {
        this.failListener = cancelListener;
    }

    /**
     * 上传参数和文件
     *
     * @return
     */
    public void postFile(final String text,
                         final RequestStringListener stringListener) {
        if (!isNetworkConnect(activity)) {
            whetherOpenNet();
            return;
        }
        showPd(text);
        Runnable task = new Runnable() {

            @Override
            public void run() {
                try {
                    final String result = okPostFileResult();
                    LogUtil.e("上传返回结果: " + result);
                    if (result != null && !"".equals(result)) {
                        if (!isAcountValue(result)) {
                            SpUtil.getInstance().savaBoolean(
                                    SharedPreferanceKey.IS_RELOGIN, true);
                            LoginInfo.getInstance(activity).cancelLogin(
                                    activity);
                        }
                    }
                    if (requestThread.isInterrupted()) {
                        showLog("is interrupted");
                        return;
                    }
                    if (result == null || TextUtils.isEmpty(result)) {
                        netError();
                        return;
                    }
                    post(new Complete() {

                        @Override
                        public void run() {
                            super.run();
                            if (stringListener != null) {

                                if (JSONUtil.isSuccess(result)) {
                                    stringListener.onComplete(result);
                                } else {
                                    String msg = JSONUtil.getMessage(result);
                                    if (!StringUtil.isEmpty(msg)) {
                                        Toast.makeText(activity, JSONUtil.getMessage(result), Toast.LENGTH_SHORT).show();
                                    }
                                }

                            }
                        }
                    });
                } catch (Exception e) {
                    netError();
                    e.printStackTrace();
                }

            }
        };
        requestThread = new Thread(task);
        requestThread.start();
    }

    public String okPostFileResult() {

        if (okHttpClient == null) {
            okHttpClient = getOkHttpClient();
        }
        MultipartBody.Builder builder = new MultipartBody.Builder().setType(MultipartBody.FORM);
        if (params != null) {
            md5Map(params);   // FIXME: 17/9/19 上传图片加上MD5加密
            for (String key : params.keySet()) {
                // TODO: 17/8/31  bug 没有签名
                builder.addFormDataPart(key, params.get(key).toString());

            }


            try {
                StringBuilder builder1 = new StringBuilder();
                for (String name : params.keySet()) {
                    builder1.append("&"
                            + URLEncoder.encode(name, "utf-8")
                            + "="
                            + URLEncoder.encode(params.get(name).toString(),
                            "utf-8"));

                    builder1.deleteCharAt(0);
                }
                LogUtil.e("get file url ------> " + "\n" + path + builder1.toString());
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
        }
        if (files != null) {
            for (String file : files.keySet()) {
                RequestBody body = RequestBody.create(MediaType.parse("image/*"), files.get(file));
                builder.addFormDataPart("file", files.get(file).getName(), body);
            }
        }
        Request request = new Request.Builder().url(path).post(builder.build()).tag(activity).build();
        // readTimeout("请求超时时间" , 时间单位)
        String data = "";
        try {
            Response response = okHttpClient.newCall(request).execute();
            data = response.body().string();
            LogUtil.e("post file data: " + data);
        } catch (Exception e) {
            LogUtil.e("file exception: " + e.toString());
            e.printStackTrace();
        }
        return data;
    }

    private String getUserAgent() throws NameNotFoundException {

        PackageInfo packageInfo = App.getContext().getPackageManager().getPackageInfo(
                App.getContext().getPackageName(), 0);
        StringBuilder sb = new StringBuilder(Constant.APP_ID);
        sb.append('/' + packageInfo.versionName + '_' + packageInfo.versionCode)
                .append("/Android")
                .append("/" + android.os.Build.VERSION.RELEASE)
                .append("/" + android.os.Build.MODEL)
                .append("/" + new SIMCardUtil(App.getContext()).getImsi())
                .append("/channel"
                        + Utils.getAppMetaData(App.getContext(), "UMENG_CHANNEL"));
        return sb.toString();

    }

    public interface NetListener {
        /**
         * 返回字符串
         */
        void onError(String result);

        void onComplete(String result);
    }

    /**
     * 请求string的监听
     */
    public abstract static class RequestStringListener implements NetListener {
        /**
         * 返回字符串
         */
        public abstract void onComplete(String result);

        @Override
        public void onError(String result) {
            if (JSONUtil.getCode(result) == 8000) {
                //token过期
                LoginInfo.getInstance(App.getContext()).cancelLogin(App.getContext());
                App.getContext().sendBroadcast(new Intent(Constant.ACTION_LOGIN_LOGINOUT));
            }
            Toast.makeText(App.getContext(), JSONUtil.getMessage(result), Toast.LENGTH_SHORT).show();
        }
    }

    /**
     * 请求string的监听
     */
    public abstract static class DataListener implements NetListener {
        /**
         * 返回字符串
         */
        public abstract void onComplete(String data);

        @Override
        public void onError(String result) {
            if (JSONUtil.getCode(result) == 8000) {
                //token过期
                LoginInfo.getInstance(App.getContext()).cancelLogin(App.getContext());
                App.getContext().sendBroadcast(new Intent(Constant.ACTION_LOGIN_LOGINOUT));
            }
            Toast.makeText(App.getContext(), JSONUtil.getMessage(result), Toast.LENGTH_SHORT).show();
        }
    }

    class Complete implements Runnable {
        @Override
        public void run() {
            if (pd != null) {
                try {

                    pd.cancel();
                } catch (Exception e) {
                    // TODO: handle exception
                }
            }
            requestThread.interrupt();
        }
    }


}
